package com.glory.hikvisionmobile.activity;

import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.LotScrapCancelListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.LotScrap.ScrapBean;
import com.glory.hikvisionmobile.bean.LotScrap.ScrapListBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Lot_LotScrapCancelActivity extends BaseActivity {

    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvStepDetails)
    TextView tvStepDetails;
    @BindView(R.id.tvRecipe)
    TextView tvRecipe;
    @BindView(R.id.tvProductDetails)
    TextView tvProductDetails;
    @BindView(R.id.tvLotNumber)
    TextView tvLotNumber;
    @BindView(R.id.tvScrapCode)
    TextView tvScrapCode;
    @BindView(R.id.ivScrapCodeListArrow)
    ImageView ivScrapCodeListArrow;
    @BindView(R.id.flScrapCodeList)
    FrameLayout flScrapCodeList;
    @BindView(R.id.etRemarks)
    FreeUI_ClearEditText etRemarks;
    @BindView(R.id.etScrapNum)
    FreeUI_ClearEditText etScrapNum;
    @BindView(R.id.rvScrapList)
    RecyclerView rvScrapList;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.list_tv5)
    TextView listTv5;
    @BindView(R.id.tvRecipeDesc)
    TextView tvRecipeDesc;
    @BindView(R.id.tvPartName)
    TextView tvPartName;
    @BindView(R.id.etScrapNumber)
    FreeUI_ClearEditText etScrapNumber;
    @BindView(R.id.llScrapCancelLayout)
    LinearLayout llScrapCancelLayout;
    @BindView(R.id.llScrapCancelPartLayout)
    LinearLayout llScrapCancelPartLayout;
    private FreeUI_GeneralPop codePop;
    private String cancelScrapCode;
    private LotScrapCancelListAdapter scrapListAdapter;
    private List<ScrapListBean> scrapListBeans;
    private String subUnitType;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_lot_scrap_cancel;
    }

    @Override
    protected void initView() {
        initListView();
        rvScrapList.setLayoutManager(new LinearLayoutManager(Lot_LotScrapCancelActivity.this));
        rvScrapList.setItemAnimator(new DefaultItemAnimator());
        rvScrapList.addItemDecoration(new DividerItemDecoration(Lot_LotScrapCancelActivity.this, 1));
        scrapListAdapter = new LotScrapCancelListAdapter(null);
        scrapListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        scrapListAdapter.isFirstOnly(true);
        scrapListAdapter.setContext(this);
        rvScrapList.setAdapter(scrapListAdapter);
        initEdit(etLot, s -> requestData(s));

        FreeApi_EditTextUtils.setEditTextListener(etScrapNum, this, s -> {
            searchLot(s);
        });
    }

    private void searchLot(String commentID) {
        String contain = "N";
        if (scrapListBeans.size() <= 0) {
            showToast("未请求到数据", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(cancelScrapCode)) {
            showToast("请选择取消报废码", false);
            return;
        }

        for (int i = 0; i < scrapListBeans.size(); i++) {
            if (scrapListBeans.get(i).getComponentId().equals(commentID)) {
                contain = "Y";
                ScrapListBean item = scrapListAdapter.getItem(i);
                item.setCheck(true);
                item.setUnActionCode(cancelScrapCode);
                scrapListAdapter.notifyItemChanged(i);
                break;
            }
        }

        if (contain.equals("N")) {
            showToast("未查询到当前组件号", false);
        }
    }

    private void requestData(String lotID) {
        JsonObject map = new JsonObject();
        map.addProperty("lotId", lotID);
        map.addProperty("actionType", "");
        NetUtils.requestDara("HIK.PdaLotUnScrap", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ScrapBean>>(
                new TypeToken<BaseResponseBean<ScrapBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ScrapBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    ScrapBean scrapBean = response.body().getBody();
                    tvLotNumber.setText(scrapBean.getMainQty());
                    tvStepDetails.setText(scrapBean.getStepDesc());
                    tvRecipe.setText(scrapBean.getRecipeName());
                    tvProductDetails.setText(scrapBean.getPartDesc());
                    tvRecipeDesc.setText(scrapBean.getRecipeDesc());
                    tvPartName.setText(scrapBean.getPartName());
                    scrapListBeans = scrapBean.getxPdaComponents();
                    scrapListAdapter.setNewData(scrapListBeans);
                    subUnitType = scrapBean.getSubUnitType();
                    if (subUnitType.equals("ComponentUnit")){
                        llScrapCancelLayout.setVisibility(View.GONE);
                        llScrapCancelPartLayout.setVisibility(View.VISIBLE);
                    }else {
                        llScrapCancelPartLayout.setVisibility(View.GONE);
                        llScrapCancelLayout.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ScrapBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaLotUnScrap");
            }
        });
    }

    @Override
    protected void initData() {
        NetUtils.getSelectorList("UnScrapCode", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                if (codePop == null) {
                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flScrapCodeList.getWidth(), list, ivScrapCodeListArrow, (codeS, i) -> {
                        tvScrapCode.setText(codeS);
                        cancelScrapCode = codeS.split("/")[0];
                        scrapListAdapter.setScrapCode(cancelScrapCode);
                    });

                }
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("批次取消报废");
        freeUI_titleView.setRightListener("刷新", v -> {

            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    if (editIsEmpty(etLot, "批次号不能为空")) {
                        etRemarks.setText("");
                        etScrapNum.setText("");
                        scrapListAdapter.getSelectorData().clear();
                        tvScrapCode.setText("");
                        etScrapNumber.setText("");
                        scrapListAdapter.setScrapCode("");
                        requestData(etLot.getText().toString().trim());

                    }
                }
            });
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.flScrapCodeList, R.id.tvReplay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flScrapCodeList:
                if (codePop == null) {
                    showToast("未请求到取消报废码列表", false);
                    return;
                }
                if (codePop.isShowing()) {
                    codePop.dismiss();
                } else {
                    FreeApi_PopUtils.setArrowShow(ivScrapCodeListArrow);
                    codePop.showAsDropDown(flScrapCodeList, 0, 0);
                }
                break;
            case R.id.tvReplay:

                initPermission("Submit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        if (FreeApi_StringUtils.isEmpty(cancelScrapCode)){
                            showToast("取消报废码为空", false);
                            return;
                        }

                        if (etRemarks.getText().toString().trim().length() == 0) {
                            showToast("请输入备注", false);
                            return;
                        }

                        if (subUnitType.equals("ComponentUnit")){
                            if (scrapListAdapter.getSelectorData().size() <= 0) {
                                showToast("当前未选中报废组件", false);
                                return;
                            }
                            DialogUtils.showLoginDialog(Lot_LotScrapCancelActivity.this, Constant.CURRENT_USER, () -> submit(), getSupportFragmentManager());
                        }else {
                            int scrapNum = Integer.parseInt(etScrapNumber.getText().toString().trim());
                            if (scrapNum <= 0){
                                showToast("取消报废数量不能小于0", false);
                                etScrapNumber.setText("");
                                etScrapNumber.requestFocus();
                                return;
                            }
                            int qtyNum = Integer.parseInt(tvLotNumber.getText().toString().trim());
                            if (scrapNum > qtyNum){
                                showToast("取消报废数量不能大于批数量", false);
                                etScrapNumber.setText("");
                                etScrapNumber.requestFocus();
                            }else {
                                DialogUtils.showLoginDialog(Lot_LotScrapCancelActivity.this, Constant.CURRENT_USER, () -> submit(), getSupportFragmentManager());
                            }
                        }
                    }
                });
                break;
        }
    }

    private void submit() {
        JsonObject json = new JsonObject();
        json.add("XPdaComponent", new JsonParser().parse(new Gson().toJson(scrapListAdapter.getSelectorData())).getAsJsonArray());
        JsonObject map = new JsonObject();
        map.addProperty("lotId", etLot.getText().toString().trim());
        map.addProperty("actionType", "UnScrap");
        map.addProperty("scrapComment", etRemarks.getText().toString().trim());
        map.add("xPdaComponents", json);
        map.addProperty("actionCode",cancelScrapCode);
        map.addProperty("scrapQty",etScrapNumber.getText().toString().trim());
        NetUtils.requestDara("HIK.PdaLotUnScrap", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ScrapBean>>(
                new TypeToken<BaseResponseBean<ScrapBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ScrapBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    if (FreeApi_StringUtils.isEmpty(response.body().getBody().getNewLotId())){
                        showConfirmDialog("取消报废成功");
                    }else {
                        showConfirmDialog("取消报废成功,新批次：" + response.body().getBody().getNewLotId());
                    }

                    etRemarks.setText("");
                    etScrapNum.setText("");
                    scrapListAdapter.getSelectorData().clear();
                    scrapListBeans.clear();
                    tvScrapCode.setText("");
                    etScrapNumber.setText("");
                    scrapListAdapter.setScrapCode("");
                    requestData(etLot.getText().toString().trim());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ScrapBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaLotUnScrap");
            }
        });
    }

    private void initListView() {
        listTv1.setText("组件号");
        listTv2.setText("位置");
        listTv3.setText("报废码");
        listTv4.setText("取消报废码");
        listTv5.setText("复选框");
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv3.setVisibility(View.VISIBLE);
        listTv4.setVisibility(View.VISIBLE);
        listTv5.setVisibility(View.VISIBLE);
    }

}
